package net.chenlin.dp.ids.client.servlet;

import net.chenlin.dp.ids.client.manager.AuthCheckManager;
import net.chenlin.dp.ids.common.base.BaseResult;
import net.chenlin.dp.ids.common.constant.GlobalErrorEnum;
import net.chenlin.dp.ids.common.entity.SessionData;
import net.chenlin.dp.ids.common.util.JsonUtil;
import net.chenlin.dp.ids.common.util.WebUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * web用户登录状态校验servlet，返回json支持跨域
 * @author zcl<yczclcn@163.com>
 */
public class WebAuthStatusServlet extends HttpServlet {

    private AuthCheckManager authCheckManager;

    private static final long serialVersionUID = 8700620723419494542L;

    public WebAuthStatusServlet(AuthCheckManager authCheckManager) {
        this.authCheckManager = authCheckManager;
    }

    /**
     * get请求
     * @param req
     * @param resp
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        SessionData sessionData = authCheckManager.checkWebSession(req);
        if (sessionData == null) {
            BaseResult notLoginRes = GlobalErrorEnum.NOT_LOGIN.getResult();
            String json = WebUtil.jsonp(JsonUtil.toStr(notLoginRes));
            WebUtil.write(resp, json);
            return;
        }
        BaseResult hasLoginRes = GlobalErrorEnum.HAS_LOGIN.getResult();
        hasLoginRes.setRespData(sessionData);
        String json = JsonUtil.toStr(hasLoginRes);
        WebUtil.write(resp, WebUtil.jsonp(json));
    }

    /**
     * post请求
     * @param req
     * @param resp
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        this.doGet(req, resp);
    }

}
